package houxb.cn.cmmiinstitute;

import cn.hutool.core.date.DateUtil;
import com.alibaba.excel.EasyExcel;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.*;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.util.*;

import static cn.hutool.core.date.DatePattern.PURE_DATETIME_FORMAT;

public class Script {
    private final static String LINE_SEPARATOR = System.lineSeparator();
    private final static String CONFIG_FILE_NAME = "config.properties";

    public static void main(String[] args) throws IOException, InterruptedException {
        Properties prop = new Properties();
        final String fileName, stageId, cookies;
        File file = new File(".\\" + CONFIG_FILE_NAME);
        if (file.exists()) {
            try (FileInputStream input = new FileInputStream(file)) {
                prop.load(new InputStreamReader(input, StandardCharsets.UTF_8));
            }
        } else {
            try (InputStream input = Script.class.getClassLoader().getResourceAsStream(CONFIG_FILE_NAME)) {
                if (input == null) {
                    throw new RuntimeException("配置文件未找到!");
                }
                prop.load(new InputStreamReader(input, StandardCharsets.UTF_8));
            }
        }
        // 读取属性（带默认值）
        fileName = prop.getProperty("fileName");
        stageId = prop.getProperty("stageId");
        cookies = prop.getProperty("cookies");
        System.out.println("接收到的参数如下：");
        System.out.println("  文件名称：" + fileName + " StateId：" + stageId + " Cookies：" + cookies);
        if (fileName == null || fileName.trim().isEmpty()) {
            System.out.println("文件名称不能为空！");
            return;
        }
        if (stageId == null || stageId.trim().isEmpty()) {
            System.out.println("StateId不能为空！");
            return;
        }
        if (cookies == null || cookies.trim().isEmpty()) {
            System.out.println("Cookies不能为空！");
            return;
        }
        System.out.println(cookies.equals(".AspNetCore.Antiforgery.cdV5uW_Ejgc=CfDJ8A4ZgetFTVVHrCjGvMl8x-98x5TYbG6jkm6rI-dg_SPz9W5z1fFlViVLnfMbZkeu1Dd7ii570mAT6VD6oFQZYJHR8rmbI0zujEm0V-xXnNglKJ1SU_jtgPLb2lJcJhEXgSlKWaHgNud53qv9ix-vXFY; .AspNetCore.Session.Public=CfDJ8A4ZgetFTVVHrCjGvMl8x%2B8SJvQ3orkbFqBVv04OyoVcEQhwqfTmpn1nZ0WD6B2Fw0cS9OCHbKfB0y%2FyLyn8Sp9787oQ4%2FtlujSnoxYi2rOt2XkLpgFph5g%2F6LGAyXhsUGl6lFceM%2BwezElG8gknMM%2FAediJkt4sNF1WZkT%2BDzDC; ARRAffinity=14bef14bf2e9b76694bc9b082cbb3443fa0028693a605a2fbe176639caf2e343; ARRAffinitySameSite=14bef14bf2e9b76694bc9b082cbb3443fa0028693a605a2fbe176639caf2e343; _ga=GA1.1.207095652.1740451428; ai_user=gwaIiBfPvWR2QnBvfJUwxG|2025-02-25T02:43:48.489Z; ARRAffinity=9a4ccea8379f299e8d7188a1e64268fdd53fa391960ddbaf1933188eede43423; ARRAffinitySameSite=9a4ccea8379f299e8d7188a1e64268fdd53fa391960ddbaf1933188eede43423; ai_session=xujAIms4siMWL9tjcm28zY|1740534269309|1740534330528; _ga_GZC8QJ4TNB=GS1.1.1740534269.5.1.1740534333.0.0.0"));
        export(fileName, stageId, cookies);
    }

    public static void export(String fileName, String stateId, String cookie) throws IOException, InterruptedException {
        List<Entity> entities = new ArrayList<>();
        for (int i = 1; true; i++) {
            System.out.println("==================正在导出第 " + i + " 页==================");
            // 1. 创建 HttpClient
            HttpClient client = HttpClient.newHttpClient();
            // 2. 创建 HttpRequest
            HttpRequest request = HttpRequest.newBuilder()
                    .header("Cookie", cookie)
                    .uri(URI.create("https://pars.cmmiinstitute.com/?StateId=" + stateId + "&PageNumber=" + i))
                    .GET()
                    .build();
            // 3. 发送请求并获取响应
            HttpResponse<String> response = client.send(
                    request,
                    HttpResponse.BodyHandlers.ofString()
            );
            Document document = Jsoup.parse(response.body());
            Elements itemCard = document.select(".card.appraisal-card");
            if (itemCard.isEmpty()) {
                break;
            }
            for (Element ele : itemCard) {
                Entity entity = new Entity();
                entities.add(entity);
                entity.setCorporateName(ele2Str(ele.select(".appraisal-card__header .item-card__title.appraisal-card__org-names a div")));
                entity.setId(ele2Str(ele.select(".appraisal-card__header .appraisal-card__id.item-card__title")).replace("ID: ", ""));
                Elements rows = ele.select(".row");
                // 第一行
                Element element = rows.get(0);
                Elements children = element.children();
                entity.setTeamLeader(ele2Str(children.get(0).select("small")));
                entity.setSponsors(ele2Str(children.get(1).select("small")));
                entity.setPartner(ele2Str(children.get(2).select("small")));
                // 第二行
                element = rows.get(1);
                children = element.children();
                entity.setOuName(ele2Str(children.get(0).select(".appraisal-card__target small")));
                entity.setAppraisalValidity(ele2Str(children.get(1).select("small")));
                // 第四行
                element = rows.get(3);
                children = element.children();
                entity.setDomain(ele2Str(children.get(0).select("small")));
                entity.setLevel(ele2Str(children.get(1).select("small")));
            }
        }
        File file = new File(".\\" + fileName + "_" + DateUtil.format(new Date(), PURE_DATETIME_FORMAT) + ".xlsx");
        if (!file.exists()) {
            if (!file.createNewFile()) {
                System.out.println("文件（" + file.getAbsolutePath() + "）创建失败！");
                return;
            }
        }
        // 这里 需要指定写用哪个class去写，然后写到第一个sheet，名字为模板 然后文件流会自动关闭
        // 如果这里想使用03 则 传入excelType参数即可
        EasyExcel.write(file, Entity.class).sheet("模板").doWrite(entities);
    }

    private static String ele2Str(Elements ele) {
        StringJoiner stringJoiner = new StringJoiner(LINE_SEPARATOR);
        ele.forEach(e -> {
            String str;
            if (e != null && !(str = e.text()).trim().isEmpty()) {
                stringJoiner.add(str);
            }
        });
        return stringJoiner.toString();
    }
}